package com.lt.flashcard.view;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.event.UploadEvent;

import com.lt.flashcard.model.service.Repository;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;

public class ImageBrowserVm {

    @Init
    public void init() {

    }

    public List<String> getImages() {
        GridFS grid = Repository.getInstance().getGridFS();
        List<String> lst = new ArrayList<String>();

        if (StringUtils.isNotBlank(search)) {
            lst.add(search);
        } else {
            int i = 0;
            DBCursor cur = grid.getFileList();
            while (cur.hasNext()) {
                DBObject o = cur.next();
                lst.add(String.valueOf(o.get("_id")));
                i++;
                if (i > 100) {
                    break;
                }
            }
        }

        return lst;
    }

    @NotifyChange("images")
    @Command
    public void delete(@BindingParam("id") String id) {
        Repository repo = Repository.getInstance();
        // repo.deleteBinaryData(id);
    }

    private String search;

    @NotifyChange("images")
    @Command
    public void dosearch() {

    }

    public String getSearch() {
        return search;
    }

    public void setSearch(String search) {
        this.search = search;
    }

    @NotifyChange("images")
    @Command
    public void upload(@BindingParam("event") UploadEvent event) {
        /*Repository repo = Repository.getInstance();
        Media media = event.getMedia();
        repo.saveBinaryData(media.getStreamData(), media.getName());*/
    }
}
